package com.sx.zongzhi.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.ServiceRecordAdapter;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.ServiceRecordBean;
import com.sx.zongzhi.bean.ServiceSearchBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.presenter.ServiceRecordPest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IServiceRecordView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * 服务记录
 */
public class ServiceRecordActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        View.OnClickListener,IServiceRecordView{

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.imvAdd)
    ImageView imvAdd;
    @BindView(R.id.tv_Total)
    TextView tv_Total;
    private Disposable disposable;
    /**筛选条件*/
    private int currentPage=1;
    private String orgId="";
    private ServiceSearchBean serviceSearchBean;

    private ServiceRecordAdapter serviceRecordAdapter;
    private List<ServiceRecordBean.RowsBean> recordBeanList=new ArrayList<>();
    private PopupWindow selectPop;
    private ServiceRecordPest recordPest;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_household);
        ButterKnife.bind(this);
        setTitleName(R.string.service_record);
        imvAdd.setVisibility(View.GONE);
        setRightImage(R.mipmap.icon_nav_search);
        recordPest=new ServiceRecordPest(this);
        initView();
        onRefresh();
    }

    private void initView() {
        IDataStorage dataStorage= DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        UserBean userBean = dataStorage.load(UserBean.class,getPackageName());
        orgId = userBean.getId();
        if (!"片组片格".equals(userBean.getOrg().getOrgLevel().getDisplayName())){
            setRightImage2(R.mipmap.icon_nav_position);
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        serviceRecordAdapter = new ServiceRecordAdapter(this,R.layout.item_work_log_list,recordBeanList);
        serviceRecordAdapter.setEmptyView(View.inflate(this,R.layout.load_error_view,null));
        recyclerView.setAdapter(serviceRecordAdapter);
        serviceRecordAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPage++;
                loadList();
            }
        },recyclerView);
        serviceRecordAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(ServiceRecordActivity.this,ServiceRecordDetailActivity.class)
                .putExtra("ServiceRecordDetailId",recordBeanList.get(position).getId()));
            }
        });
        //订阅筛选组织机构
        disposable= MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if ("ServiceRecordActivity".equals(bean.getRequest())) {
                            if (bean.getType()==0) {//获取组织机构
                                OrganizingBean oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    orgId = oBean.getId();
                                    currentPage=1;
                                    loadList();
                                }
                            }
                            if (bean.getType()==1){//查询返回
                                serviceSearchBean= (ServiceSearchBean) bean.getMsg();
                                currentPage=1;
                                loadList();
                            }
                            if (bean.getType()==2){//新增成功
                                onRefresh();
                            }
                        }
                    }
                });
    }


    @OnClick({R.id.imv_Right,R.id.imv_Right2,R.id.imvAdd})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.imv_Right:
                startActivity(new Intent(ServiceRecordActivity.this,ServiceRecordSearchActivity.class)
                .putExtra(Global.ACTIVITY_FRAGMENT,"ServiceRecordActivity"));
                break;
            case R.id.imv_Right2:
                startActivity(new Intent(ServiceRecordActivity.this,OrganizingActivity.class)
                 .putExtra(Global.ACTIVITY_FRAGMENT,"ServiceRecordActivity"));
                break;
            case R.id.imvAdd:
                showPopupSelect();
                break;
        }
    }


    @Override
    public void onRefresh() {
        currentPage=1;
        serviceSearchBean=null;
        loadList();
    }

    private void loadList() {
        recordPest.getServiceRecordList(orgId,serviceSearchBean,currentPage,10);
    }

    /**
     * 显示选择文件的弹窗
     */
    private void showPopupSelect() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_file, null);
        if (selectPop == null) {
            selectPop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            selectPop.setTouchable(true);
            selectPop.setOutsideTouchable(false);
            selectPop.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
        }
        TextView textView= (TextView) view.findViewById(R.id.tv_File);
        textView.setText("文字");
        textView.setOnClickListener(this);
        view.findViewById(R.id.tv_Picture).setOnClickListener(this);
        view.findViewById(R.id.tv_Audio).setOnClickListener(this);
        view.findViewById(R.id.tv_Video).setOnClickListener(this);
        view.findViewById(R.id.tv_Cancel).setOnClickListener(this);
        selectPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_File:
                startAddService(0);
                break;
            case R.id.tv_Picture:
                startAddService(1);
                break;
            case R.id.tv_Audio:
                startAddService(2);
                break;
            case R.id.tv_Video:
                startAddService(3);
                break;
            case R.id.tv_Cancel:
                break;
        }
        selectPop.dismiss();
    }

    @Override
    protected void onDestroy() {
        if (disposable!=null&&disposable.isDisposed()){
            disposable.dispose();
        }
        super.onDestroy();
    }

    private void startAddService(int type){
        startActivity(new Intent(this,AddServiceRecordActivity.class).putExtra("FileType",type)
                .putExtra(Global.ACTIVITY_FRAGMENT,"ServiceRecordActivity"));
    }

    @Override
    public void getServiceRecordList(ServiceRecordBean recordBean) {
        if (recordBean.getPermission() != null){
            if (recordBean.getPermission().isAddServiceRecord()){
                imvAdd.setVisibility(View.VISIBLE);
            }else {
                imvAdd.setVisibility(View.GONE);
            }
        }
        swipeRefreshLayout.setRefreshing(false);
        if (currentPage==1){
            recordBeanList.clear();
            serviceRecordAdapter.setNewData(recordBeanList);
        }
        if (recordBean.getRows()!=null) {
            recordBeanList.addAll(recordBean.getRows());
        }
        serviceRecordAdapter.notifyDataSetChanged();
        if(recordBeanList.size()>=recordBean.getRecords()){
            serviceRecordAdapter.loadMoreEnd();
        }else {
            serviceRecordAdapter.loadMoreComplete();
        }
        tv_Total.setText("共"+recordBean.getTotal()+"条数据");
    }

    @Override
    public void showError(String message) {
        swipeRefreshLayout.setRefreshing(false);
        ToastUtils.showToast(this,message);
    }
}
